package com.ParkingManager.app.service.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ParkingManager.app.config.AlipayConfig;
import com.ParkingManager.app.service.AlipayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
@Service
@Transactional
/**
 * 
 * @author 庞晓军
 * @description 支付接口实现类
 */
public class AlipayServiceImpl implements AlipayService {


	/**
	 * 实现支付宝支付调用接口方法
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	 public void aliPay(HttpServletResponse response, HttpServletRequest request,double price,int id) throws IOException {
		//编码格式
        response.setContentType("text/html;charset=utf-8");

        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
        //同步地址
        aliPayRequest.setReturnUrl(AlipayConfig.return_url+"?id="+id);
        //异步地址
        aliPayRequest.setNotifyUrl(AlipayConfig.notify_url+"?id="+id);

        //商户订单号，后台可以写一个工具类生成一个订单号，必填
        long timeStart = Calendar.getInstance().getTimeInMillis();//取时间       
        String order_number =  "alipay_" + timeStart;// 订单号
        
        //付款金额，从前台获取，必填
        String total_amount = new String(Double.toString(price));      
        //订单名称，必填
        String subject = new String("支付宝扫码测试");
        ////填充业务参数
        aliPayRequest.setBizContent("{\"out_trade_no\":\"" + order_number + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        try {
        	//调用SDK生成表单
            result = alipayClient.pageExecute(aliPayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //输出
        out.println(result);
        

	}

}
